<?php
/*
 * @author eBIZ Team <dev@jungo.com.cn>
 * @copyright  Copyright (c) , ShenZhen JunGO Technology Co., Ltd. All rights reserved.
 * @license  Commercial authorization, unauthorized use and modification are prohibited
 * @url www.jungo.com.cn
 */

namespace ckeeper\http;



use Qcloud\Cos\Client as CosClient;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\UploadManager;
use Selibra\Di\Annotations\Component;
use Selibra\Http\Annotations\Controller;
use Selibra\Http\Annotations\Route;

#[Component]
#[Controller("/upload",self::class)]
class Upload extends http
{

    /**
     * 不需要权限验证
     * @var bool
     */
    protected bool $accessAuth = false;


    /**
     * 图片上传
     * @return mixed
     * @throws \Exception
     */
    #[Route("/picture")]
    public function picture()
    {
        $file = $this->getRequest()->getFile('file');
        if (empty($file)) {
            return $this->error("UploadError.", [], 500);
        }

        // 要上传文件的本地路径
        $filePath = str_replace('\\', '/', $file['tmp_name']);//文件路径，必须是本地的。

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);  //后缀

        // 上传到腾讯后保存的文件名
        $key = substr(md5($file['name']), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;

        $cosClient = new CosClient([
            'region' => 'ap-guangzhou',
            'credentials' => [
                'secretId' => 'AKIDuhIgqnV2MciaFgwzymLekaAUYMuBD2as',
                'secretKey' => '5wZx5zhAQSGpAG6oJbgW8VdWIsDKCqFP',
            ]
        ]);

        try {
            $cosClient->putObject(array(
                'Bucket' => 'yx-1258247706',
                'Key' => $key,
                'Body' => fopen($filePath, 'rb')));
            $url = 'https://img.junui.cn/' . $key;
        } catch (\Exception $e) {
            return $this->error("上传失败", [], 500);
        }

        return $this->success("上传成功.", [
            'url' => $url
        ]);
    }


}
